package com.tutu.jwt.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tutu.jwt.entity.User;
import com.tutu.jwt.service.UserService;
import com.tutu.jwt.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Program: SpringBoot
 * @Description:
 * @Author: JK.TuTu
 * @ @Version: 1.0
 * @Create: 2022-11-28 19:24
 **/
@RequestMapping("user")
@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录接口
     * @param user
     * @return
     */
    @GetMapping("/login")
    public Map<String,Object> login(User user){
        log.info("当前登录用户:{}",user);
        Map<String,Object> map = new HashMap<>();
        try{
            User userDB = userService.login(user);
            Map<String,String> payload = new HashMap<>();
            payload.put("id",String.valueOf(user.getId()));
            payload.put("username",user.getUsername());
            //生成JWT令牌
            String token = JWTUtils.createToken(payload);
            map.put("state",true);
            map.put("msg","认证成功");
            map.put("token",token);
        }catch (Exception e) {
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    @PostMapping("remove")
    public Map<String, Object> register(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        //处理业务逻辑
        String token = request.getHeader("token");
        DecodedJWT decodedJWT = JWTUtils.verifyToken(token);
        log.info("用户id:{}",decodedJWT.getClaim("id").asString());
        log.info("用户姓名:{}",decodedJWT.getClaim("username").asString());
        map.put("state",true);
        map.put("msg","请求成功");
        return map;
    }
}
